package com.star.filter;

import com.star.exception.ServiceException;
import com.star.exception.SystemException;
import com.star.security.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 授权过滤器
 *
 * @author tanyapeng
 * @date 2021/3/8
 */
@Slf4j
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private TokenManager tokenManager;

    private StringRedisTemplate stringRedisTemplate;

    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, StringRedisTemplate stringRedisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 过滤权限
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        try {
            // 获取当前认证成功用户权限信息
            UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
            if (authRequest == null) {
                throw new ServiceException(20001, "用户无权限!");
            }
            // 如果有权限信息，放到权限上下文中
            SecurityContextHolder.getContext().setAuthentication(authRequest);
            chain.doFilter(request, response);
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("doFilterInternal error - {},{}", ExceptionUtils.getStackTrace(e), request, response, chain);
            throw new SystemException(10001, "过滤权限出错");
        }
    }

    /**
     * 获取当前认证成功用户权限信息
     *
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        try {
            //从header获取token
            String token = request.getHeader("token");
            if (token != null) {
                //从token获取用户名
                String username = tokenManager.getUserInfoFromToken(token);
                //从redis获取对应权限列表
                List<String> permissionValueList = getPermissionList(username);
                Collection<GrantedAuthority> authority = new ArrayList<>();
                for (String permissionValue : permissionValueList) {
                    SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                    authority.add(auth);
                }
                return new UsernamePasswordAuthenticationToken(username, token, authority);
            }
            return null;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("getAuthentication error - {},{}", ExceptionUtils.getStackTrace(e), request);
            throw new SystemException(10001, "获取当前认证成功用户权限信息出错");
        }
    }

    /**
     * 在redis里查询用户对应权限列表
     *
     * @param username
     * @return
     */
    private List<String> getPermissionList(String username) {
        try {
            return stringRedisTemplate.opsForList().range(username, 0, -1);
        } catch (Exception e) {
            log.error("addToken error - {},{},{}", ExceptionUtils.getStackTrace(e), username);
            throw new SystemException(10002, "添加token出错");
        }
    }

}
